package com.winsdom.service.impl;

import com.winsdom.constant.MessageConstant;
import com.winsdom.context.BaseContext;
import com.winsdom.dto.AccountInformationDTO;
import com.winsdom.dto.CategoryTreeNodes;
import com.winsdom.dto.SysUserDTO;
import com.winsdom.entity.SysUser;
import com.winsdom.entity.SysUserRole;
import com.winsdom.exception.BaseException;
import com.winsdom.exception.IllegalArgumentException;
import com.winsdom.exception.PhoneExistsException;
import com.winsdom.mapper.CategoryMapper;
import com.winsdom.mapper.SysCodeRuleMapper;
import com.winsdom.mapper.SysUserMapper;
import com.winsdom.mapper.SysUserRoleMapper;
import com.winsdom.result.PageResult;
import com.winsdom.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winsdom.utils.PasswordUtil;
import com.winsdom.vo.AccountInformationVO;
import com.winsdom.vo.CodeRuleVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-05-12
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private final SysUserMapper sysUserMapper;
    private final SysCodeRuleMapper sysCodeRuleMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final CategoryMapper categoryMapper;
    /**
     * 查询全部账号
     * @param accountInformationDTO
     * @return
     */
    @Override
    public PageResult getAllAccount(AccountInformationDTO accountInformationDTO) {
        if (accountInformationDTO.getPageNum()<1){
            throw new IllegalArgumentException("页码不能小于 1");
        }
        if (accountInformationDTO.getPageSize()<1){
            throw new IllegalArgumentException("每页大小不能小于 1");
        }
        //查询账号数据
        List<AccountInformationVO> allAccount = sysUserMapper.getAllAccount(accountInformationDTO);
        //单独查询总记录数
        Long total=sysUserMapper.selectTotalCount(accountInformationDTO);

        PageResult result = new PageResult();
        result.setTotal(total);
        result.setRecords(allAccount);
        result.setPageNum(accountInformationDTO.getPageNum());
        result.setPageSize(accountInformationDTO.getPageSize());
        return result;
    }

    /**
     * 新增用户
     * @param sysUserDTO
     */
    @Override
    @Transactional
//    @ValidatePhone
    public void add(SysUserDTO sysUserDTO) {
        validateUserDTO(sysUserDTO);

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);


        String phone = sysUserDTO.getPhone();
        //手机号全局唯一
        SysUser existingUser = sysUserMapper.selectByPhone(phone);
        if (existingUser != null) {
            throw new PhoneExistsException(MessageConstant.PHONE_EXISTS);
        }

        sysUser.setPassword(PasswordUtil.encode(phone.substring(phone.length() - 6)));


        //根据编码规则生成账号
        Long categoryId = sysUserDTO.getCategoryId();
        String identifier=sysCodeRuleMapper.selectByCategoryId(categoryId);
        int userCount = sysUserMapper.countUsersByCategoryId(categoryId);
        String countStr = String.format("%04d", userCount + 1); // 转为4位字符串，不足补零

        sysUser.setUsername(identifier + countStr);

        log.info("新增用户: {}", sysUser);
        sysUserMapper.insert(sysUser);

        // 将用户的角色信息存储到 sys_user_role 表中
        saveUserRoles(sysUser.getId(), sysUserDTO.getRoleIds());

    }

    /**
     * 编辑用户
     * @param sysUserDTO
     */
    @Override
    @Transactional
    public void update(SysUserDTO sysUserDTO) {
        validateUserDTO(sysUserDTO);

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);

        // 校验手机号是否全局唯一（排除当前用户自身）
        String phone = sysUserDTO.getPhone();
        SysUser existingUser = sysUserMapper.selectByPhone(phone);
        if (existingUser != null && !existingUser.getId().equals(sysUser.getId())) {
            throw new PhoneExistsException(MessageConstant.PHONE_EXISTS);
        }

        baseMapper.updateById(sysUser);

        // 删除用户原来的角色关联
        sysUserRoleMapper.deleteByUserId(sysUser.getId());

        saveUserRoles(sysUser.getId(), sysUserDTO.getRoleIds());
    }

    /**
     * 获取当前用户组织树
     * @return
     */
    @Override
    public CategoryTreeNodes getCurrentUserOrganizationTree() {
        Integer userId = BaseContext.getCurrentId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        Long categoryId = sysUser.getCategoryId();

        CategoryTreeNodes realRootNode = categoryMapper.getNodeById(categoryId);

        List<CategoryTreeNodes> categoryTreeNodes = categoryMapper.getCategoryTreeNodes(categoryId);
        if (categoryTreeNodes.isEmpty()) {
            throw new BaseException("未找到对应的组织树结构");
        }

        realRootNode.setChildren(categoryTreeNodes);

        return realRootNode;
    }

    /**
     * 重置密码
     * @param id
     */
    @Override
    public void resetPassword(Long id) {
        // 1. 查询用户信息
        SysUser user = sysUserMapper.selectById(id);
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        // 2. 获取手机号并截取后六位
        String phone = user.getPhone();
        if (phone == null || phone.length() < 6) {
            throw new BaseException("手机号格式不正确，无法重置密码");
        }
        String newPassword = PasswordUtil.encode(phone.substring(phone.length() - 6));
        SysUser updateUser = new SysUser();
        updateUser.setId(id);
        updateUser.setPassword(newPassword);
        int rows = sysUserMapper.updateById(updateUser);

        if (rows == 0) {
            throw new BaseException("密码重置失败");
        }
    }

    /**
     * 获取编码规则
     * @return
     */
    @Override
    public CodeRuleVO getCodeRule() {
        Integer userId = BaseContext.getCurrentId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        Long categoryId = sysUser.getCategoryId();
        String codeRule = sysCodeRuleMapper.selectByCategoryId(categoryId);
        CodeRuleVO codeRuleVO = CodeRuleVO.builder()
                .identifier(codeRule)
                .build();
        return codeRuleVO;
    }

    /**
     * 校验用户DTO非空
     * @param sysUserDTO
     */
    private void validateUserDTO(SysUserDTO sysUserDTO) {
        if (sysUserDTO == null) {
            throw new BaseException(MessageConstant.USER_INFO_EMPTY);
        }
    }

    /**
     * 保存用户角色关联
     * @param userId
     * @param roleIds
     */
    private void saveUserRoles(Long userId, Long[] roleIds) {
        if (roleIds == null || roleIds.length == 0) {
            log.warn("用户角色ID数组为空，跳过角色关联");
            return;
        }
        for (Long roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
